package com.moli.iov.manager.activemq;

import com.moli.iov.manager.model.po.AuthoritySysUser;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

/**
 * <p>
 *  ActiveMQ 生产者
 * </p>
 *
 * @Auther: zql
 * @Date: 2018/11/28 15:23
 */
@Component("activeMQProducer")
public class ActiveMQProducer {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private ActiveMQQueue delayQueue;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;


    /**
     * 推送
     * @param expiringUser
     */
    public void send(AuthoritySysUser expiringUser, Long expriredTime){
        taskExecutor.execute(()->{
            logger.info("ActiveMQ 发送延时消息开始，入参：{}", expiringUser);
            jmsTemplate.send(delayQueue, new MessageCreator() {
                @Override
                public Message createMessage(Session session) throws JMSException {
                    ObjectMessage objectMessage = session.createObjectMessage(expiringUser);
                    objectMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, expriredTime);
                    logger.info("已发送延时消息 queue: {}, 延时时间：{}, 消息：{}", delayQueue, expiringUser, expriredTime);
                    return objectMessage;
                }
            });
            logger.info("ActiveMQ 发送延时消息完成，入参：{}", expiringUser);
        });
    }
}
